package com.dayatang.android.Activity;

import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.dayatang.android.Activity.Application.MyApplication;
import com.dayatang.android.Model.User;
import com.dayatang.android.Task.LoginTask;
import com.dayatang.android.config.Config;

public class LoginActivity extends BaseActivity {

	private EditText userEditText,pwdEditText;
	private String username,password;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_activity);
		
		userEditText = (EditText) findViewById(R.id.username_edit);
		pwdEditText = (EditText) findViewById(R.id.password_edit);
		
		InitView();
	}
	
	private void InitView() {
		String state = getIntentString();
		if (state == null) {
			if (checkIfRemember()) {                                  
				login();
			}
		} else if (state.equals(Config.LOGOUT)) {
			checkIfRemember();
		}
		((Button) findViewById(R.id.signin_button)).setOnClickListener(loginClicker);
	}
	
	private String getIntentString() {
		return getIntent().getStringExtra(Config.LOGOUT);
	}
	
	OnClickListener loginClicker = new OnClickListener() {
		public void onClick(View v) {
			if (validate()) {
				login();
			}
		}
	};
	
	private boolean validate() {
		String username = userEditText.getText().toString();
		if (username.equals("")) {
			userEditText.setError(getString(R.string.login_username_noNull));
			return false;
		}
		String pwd = pwdEditText.getText().toString();
		if(pwd.equals("")) {
			pwdEditText.setError(getString(R.string.login_password_noNull));
			return false;
		}
		return true;
	}
	
	private void login() {
		if (chkConnection()) {   
			username = userEditText.getText().toString();
			password = pwdEditText.getText().toString();
			try {
				GoActivityByResult(new LoginTask(this).execute(getServerAddress(),username, password).get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		} else {
			ToastShow(getString(R.string.network_no_connection));
		}
	}
	
	private void GoActivityByResult(String result) {
		if (result.equals(Config.USERNAMENOEXISTS)) {                    
			userEditText.setError(getString(R.string.login_username_noExists));
		} else if (result.equals(Config.PASSWORDERROR)) {
			pwdEditText.setError(getString(R.string.login_password_error));
		} else if (result.equals(Config.ERROR) || result.equals(Config.SERVERDIE) || result.equals(Config.OTHER) || result == null) {
			ManageServerInfo(result);
		} else {      
			if (saveDataToApplication(result)) {
				LoginSuccess();
			} else {
				ToastShow(getString(R.string.login_failure));
			}
		}
	}
	
	private void LoginSuccess() {
		CheckBox cb = (CheckBox)findViewById(R.id.cbRemember);		
		if (cb.isChecked()) {
			rememberMe(username,password);
		}
		Intent intent = new Intent(LoginActivity.this,WorkstationOfPMOActivity.class);
		startActivity(intent);						
		finish();
	}
	
	private boolean saveDataToApplication(String data) {
		try {
			JSONObject jsonObject = new JSONObject(data);
			
			User user = new User();
			user.setId(jsonObject.getLong("userid"));
			user.setName(jsonObject.getString("name"));
			user.setUsername(jsonObject.getString("username"));
			user.setRole(jsonObject.getString("role"));
			
			MyApplication application = (MyApplication) this.getApplication();
			application.setUser(user);
			
			return true;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;
	}
	
    public void rememberMe(String uid,String pwd) {
    	SharedPreferences sp = getPreferences(MODE_PRIVATE);	
    	SharedPreferences.Editor editor = sp.edit();			
    	editor.putString("uid", uid);							
    	editor.putString("pwd", pwd);							
    	editor.commit();
    }
    
    public boolean checkIfRemember() {
    	SharedPreferences sp = getPreferences(MODE_PRIVATE);	
    	String uid = sp.getString("uid", null);  
    	String pwd = sp.getString("pwd", null);
    	if (uid != null && pwd!= null) {
    		EditText etUid = (EditText)findViewById(R.id.username_edit);
    		EditText etPwd = (EditText)findViewById(R.id.password_edit);
    		CheckBox cbRemember = (CheckBox)findViewById(R.id.cbRemember);
    		etUid.setText(uid);
    		etPwd.setText(pwd);
    		cbRemember.setChecked(true);
    		return true;
    	}
    	return false;
    }
    
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}
}
